<template>
  <div class="app-container">
    <!-- 桌面端左右布局 -->
    <el-row :gutter="10" v-if="!isMobile">
      <el-col :span="showTree ? 6 : 0">
        <div style="display: block; margin-bottom: 15px;">
          <CourseTree :title="title" @search="getList1" />
        </div>
      </el-col>
      <el-col :span="showTree ? 18 : 24">
        <div class="course_content">
          <el-row type="flex" justify="around" style="width: 100%">
            <el-col :span="24">
              <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
                <el-form-item label="题型" prop="type">
                  <el-select v-model="queryParams.type" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>

                <el-form-item label="题干" prop="wd">
                  <el-input v-model="queryParams.wd" placeholder="请输入关键词" clearable size="small" />
                </el-form-item>
                <el-form-item label="关联知识点" prop="knowledge">
                  <el-select v-model="queryParams.knowledge" placeholder="请选择.." clearable filterable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in knowledgeOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" size="mini" @click="handleQuery" :style="{
                    backgroundColor: theme,
                    borderColor: theme,
                  }">搜索</el-button>
                  <el-button size="mini" @click="resetQuery">清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" :style="{
                backgroundColor: theme,
                borderColor: theme,
                fontWeight: 'bold'
              }" @click="handleAdd()" v-hasPermi="['question:list:add']">新建试题</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" :style="{
                backgroundColor: theme,
                borderColor: theme,
                fontWeight: 'bold'
              }" @click="handleUploadClick" v-hasPermi="['question:list:add']">批量导入试题
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" :style="{
                fontWeight: 'bold'
              }" @click="handleBatchDelete"
                :disabled="selectedRows.length === 0" v-hasPermi="['question:list:del']">批量删除
              </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" :showTree.sync="showTree" @queryTable="getList"></right-toolbar>
          </el-row>
          
          <!-- PC端表格视图 -->
          <el-table 
            :data="List" 
            size="mini" 
            style="width: 100%; margin-top: 20px" 
            align="center"
            @row-dblclick="handleUpdate" 
            v-loading="loading" 
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" min-width="40">
              <template slot-scope="scope">
                {{ (queryParams.page - 1) * queryParams.page_size + scope.$index + 1 }}
              </template>
            </el-table-column>

            <el-table-column label="题干" min-width="200">
              <template slot-scope="scope">
                <div v-html="scope.row.stem" />
              </template>
            </el-table-column>
            <el-table-column label="题库分类">
              <template slot-scope="scope">
                <span v-if="scope.row.knowledge.name">{{
                  scope.row.knowledge.name
                }}</span>

              </template>
            </el-table-column>
            <el-table-column label="题型" prop="type_name"> </el-table-column>
            <el-table-column label="分值" prop="score"> </el-table-column>
            <el-table-column type="expand" label="操作">
              <template slot-scope="scope">
                <el-row :gutter="20" type="flex" justify="start" align="middle">
                  <div class="question_list_title">
                    <div style="
                                        display: inline-flex;
                                        justify-content: start;
                                        flex-wrap: nowrap;
                                        align-items: center;
                                      ">
                      <span> {{ scope.row.type_name }}</span>
                      <span v-html="scope.row.stem"></span>
                      <span>{{ scope.row.score }}分</span>
                    </div>
                  </div>
                </el-row>
                <p v-for="item in scope.row.option" :key="item.name" style="padding-left: 42px"
                  v-html="item.name + '.' + item.content"></p>
                <el-row :gutter="10" type="flex" justify="end" align="middle">
                  <el-col :span="22" :style="{ color: theme }">正确答案：
                    <span v-show="scope.row.type == 3 && scope.row.answer[0] == 1">
                      对</span>
                    <span v-show="scope.row.type == 3 && scope.row.answer[0] == 0">
                      错</span>
                    <span v-for="(ans, index) in scope.row.answer" :key="index" v-show="scope.row.type != 3">
                      {{ ans }}</span>

                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" size="mini" :style="{ color: theme }" @click="handleUpdate(scope.row)"
                      v-hasPermi="['question:list:editor']"><i class="el-icon-edit-outline"></i>编辑题目</el-button>
                  </el-col>
                  <el-col :span="2" v-if="is_superuser">
                    <el-button type="text" size="mini" style="color: #c93228" @click="handleDelete(scope.row)"
                      v-hasPermi="['question:list:del']"><i class="el-icon-delete"></i>删除题目</el-button>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>

          <!-- PC端分页 -->
          <pagination v-if="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size"
            @pagination="getList" />
        </div>
      </el-col>
    </el-row>

    <!-- 移动端上下布局 -->
    <template v-if="isMobile">
      <!-- 移动端分类树 -->
      <div v-if="showTree" class="mobile-tree-container">
        <div class="mobile-tree-header">
          <span :style="{ color: theme }">{{ title }}</span>
          <el-button 
            type="text" 
            icon="el-icon-arrow-up" 
            @click="showTree = false" 
            :style="{ color: theme }"
            v-if="showTree">
            收起
          </el-button>
        </div>
        <CourseTree :title="title" @search="getList1" />
      </div>
      <div v-else class="mobile-tree-toggle">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-button 
              type="primary" 
              size="small" 
              icon="el-icon-arrow-down"
              @click="showTree = true"
              :style="{
                backgroundColor: theme,
                borderColor: theme,
                width: '100%',
                marginBottom: '10px',
                borderRadius: '4px',
                height: '36px'
              }">
              展开题库分类
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 移动端列表内容 -->
      <div class="course_content">
        <el-row type="flex" justify="around" style="width: 100%" class="mobile-search">
          <el-col :span="24">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" class="mobile-form">
              <el-form-item label="题型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择.." clearable size="small" @change="handleQuery">
                  <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue" />
                </el-select>
              </el-form-item>

              <el-form-item label="题干" prop="wd">
                <el-input v-model="queryParams.wd" placeholder="请输入关键词" clearable size="small" />
              </el-form-item>
              <el-form-item label="关联知识点" prop="knowledge">
                <el-select v-model="queryParams.knowledge" placeholder="请选择.." clearable filterable size="small"
                  @change="handleQuery">
                  <el-option v-for="dict in knowledgeOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" size="mini" @click="handleQuery" :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  width: '100%'
                }">搜索</el-button>
                <el-button size="mini" @click="resetQuery" style="width: 100%; margin-top: 10px;">清空</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        
        <!-- 移动端操作按钮 -->
        <div class="mobile-action-buttons">
          <el-button type="primary" size="small" icon="el-icon-plus" :style="{
            backgroundColor: theme,
            borderColor: theme,
            marginBottom: '10px'
          }" @click="handleAdd()" v-hasPermi="['question:list:add']">新建试题</el-button>
          
          <el-button type="primary" size="small" icon="el-icon-plus" :style="{
            backgroundColor: theme,
            borderColor: theme,
            marginBottom: '10px'
          }" @click="handleUploadClick" v-hasPermi="['question:list:add']">批量导入试题</el-button>
          
          <el-button type="danger" size="small" icon="el-icon-delete" :style="{
            marginBottom: '10px'
          }" @click="handleBatchDelete"
            :disabled="selectedRows.length === 0" v-hasPermi="['question:list:del']">批量删除</el-button>
        </div>
        
        <!-- 移动端卡片列表 -->
        <div class="mobile-card-list">
          <el-card 
            v-for="(item, index) in List" 
            :key="index"
            class="mobile-card"
            shadow="hover">
            <!-- 题干 -->
            <div class="mobile-card-header">
              <div class="card-title">
                <span class="question-number">{{ (queryParams.page - 1) * queryParams.page_size + index + 1 }}. </span>
                <span class="question-type" :style="{ color: theme }">【{{ item.type_name }}】</span>
                <span class="question-score">{{ item.score }}分</span>
              </div>
              <div class="card-content" v-html="item.stem"></div>
            </div>
            
            <!-- 题目分类 -->
            <div class="mobile-card-info">
              <span class="info-label">题库分类：</span>
              <span class="info-value">{{ item.knowledge.name || '无' }}</span>
            </div>
            
            <!-- 选项和答案 -->
            <div 
              v-if="expandedCards.includes(index)" 
              class="mobile-card-detail">
              <div v-for="option in item.option" :key="option.name" class="question-option">
                <div v-html="option.name + '.' + option.content"></div>
              </div>
              
              <div class="question-answer" :style="{ color: theme }">
                <span>正确答案：</span>
                <span v-show="item.type == 3 && item.answer[0] == 1">对</span>
                <span v-show="item.type == 3 && item.answer[0] == 0">错</span>
                <span v-for="(ans, ansIndex) in item.answer" :key="ansIndex" v-show="item.type != 3">
                  {{ ans }}
                </span>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="mobile-card-actions">
              <el-button type="text" @click="toggleExpand(index)">
                {{ expandedCards.includes(index) ? '收起' : '查看详情' }}
              </el-button>
              <div>
                <el-button type="text" :style="{ color: theme }" @click="handleUpdate(item)" v-hasPermi="['question:list:editor']">
                  <i class="el-icon-edit-outline"></i> 编辑
                </el-button>
                <el-button type="text" style="color: #c93228" @click="handleDelete(item)" v-hasPermi="['question:list:del']">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 移动端分页 -->
        <div class="mobile-pagination" v-if="total > 0">
          <div class="mobile-pagination-wrapper">
            <!-- 第一行：总数和每页条数 -->
            <div class="pagination-row top-row">
              <span class="el-pagination__total">共 {{ total }} 条</span>
              <el-select 
                v-model="queryParams.page_size" 
                size="mini" 
                class="el-pagination__sizes"
                @change="handleSizeChange">
                <el-option
                  v-for="item in [10, 20, 30, 50]"
                  :key="item"
                  :label="`${item}条/页`"
                  :value="item">
                </el-option>
              </el-select>
            </div>
            
            <!-- 第二行：页码导航 -->
            <div class="pagination-row bottom-row">
              <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="queryParams.page"
                :page-size="queryParams.page_size"
                layout="prev, pager, next, jumper"
                :total="total">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </template>

    <el-dialog :title="upload.title" :visible.sync="upload.open" :before-close="uploadClose" :width="isMobile ? '95%' : '500px'"
      style="padding: 10px" append-to-body>
      <el-form ref="form" :model="formData" label-width="80px" :class="{'mobile-form': isMobile}">
        <el-form-item label="选择课程">
          <el-select v-model="formData.category" filterable placeholder="请选择" size="small" :style="{ width: isMobile ? '100%' : '70%' }" clearable>
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选取文件">
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
            :data="formData" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess" :on-error="handleFileError" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                href="/file/题库模板.xls" target="_blank">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" :class="{'mobile-dialog-footer': isMobile}">
        <el-button type="primary" @click="submitFileForm" :style="{ width: isMobile ? '45%' : 'auto' }">确 定</el-button>
        <el-button @click="cancleFileForm" :style="{ width: isMobile ? '45%' : 'auto' }">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="results" :visible.sync="resultsUpload" :before-close="resultsClose" :width="isMobile ? '95%' : '500px'"
      style="padding: 10px" append-to-body>
      <el-alert type="warning">
        <template slot="title">
          <div v-html="warningTitle"></div>
        </template>
      </el-alert>
      <el-table :data="tableResultsData" height="250" border v-show="tableResultsData.length > 0"
        style="width: 100%;margin:15px 0">
        <el-table-column type="index" label="序号" />
        <el-table-column prop="" label="上传失败试题">
          <template slot-scope="scope">
            <span>{{ scope.row }}</span>
          </template>
        </el-table-column>

      </el-table>
      <el-card class="box-card" style="margin-top: 15px" v-if="failLoad">
        <div slot="header" class="clearfix">
          <span style="color: red">上传失败</span>
        </div>
        <ul class="infinite-list" v-infinite-scroll="load" style="overflow: auto; height: 200px; margin: 15px 0">
          <li v-for="(i, index) in tableResultsData.slice(0, count)" :key="index" class="infinite-list-item">
            {{ index + 1 }}、{{ i }}
          </li>
        </ul>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resultsUpload = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { getQuestion, delQuestion } from "@/api/vadmin/question/index";
import Cookies from "js-cookie";
import CourseTree from "@/components/CourseTree";
import { categoryList, listKnowledge } from "@/api/vadmin/course/course";
export default {
  name: "Course",
  components: { CourseTree },
  data() {
    return {
      // 遮罩层
      loading: true,
      showTree: true,
      resultsUpload: false, //上传结果
      tableResultsData: [],
      results: "上传完成",
      warningTitle: "",
      failLoad: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 选中的行
      selectedRows: [],

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      count: 5,
      // 用户表格数据
      courseList: null,
      form: {},
      queryParams: {
        page: 1,
        page_size: 10,
        course: "",
        type: '',
        wd: ''

      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      formData: {},
      category: '',
      categoryOptions: [],
      title: "题库分类",
      List: [],
      knowledgeOptions: [],
      courseOptions: [],
      purposeOptions: [
        {
          dictValue: 1,
          dictLabel: "培训",
        },
        {
          dictValue: 2,
          dictLabel: "认证",
        },
      ],
      typeOptions: [
        {
          dictValue: 1,
          dictLabel: "单选题",
        },
        {
          dictValue: 2,
          dictLabel: "多选题",
        },
        {
          dictValue: 3,
          dictLabel: "判断题",
        },
        {
          dictValue: 4,
          dictLabel: "问答题",
        },
      ],

      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "批量导入",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部  getToken => 获取用户token的方法
        headers: { Authorization: "JWT " + Cookies.get("token") },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/questionFile/",
      },
      screenWidth: document.body.clientWidth,
      selectAll: false,
      selectedRowKeys: [],
      expandedCards: [],
      isMobile: false,
      mediaQueryList: null
    };
  },
  computed: {
    ...mapState(["settings",'is_superuser']),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    is_superuser(){
      return this.$store.state.user.is_superuser;
    },
  },
  watch: {
    screenWidth(val) {
      this.screenWidth = val;
    }
  },
  created() {
    this.getBasicData();
    this.getCategoryOptions();

    if (this.$route.query.knowledge) {
      this.queryParams.knowledge = Number(this.$route.query.knowledge);
      this.getList();
    } else {
      this.getList();
    }
    this.getDicts("question_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getTreeselect();
    this.getknowledgeOptions();
    // 监听屏幕宽度变化
    this.mediaQueryList = window.matchMedia("(max-width: 768px)");
    this.mediaQueryList.addListener(this.handleScreenWidthChange);
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 根据isMobile状态设置树的默认显示
    if (this.isMobile) {
      this.showTree = false;
    }
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
      
      // 切换到桌面模式时自动显示树
      if (!this.isMobile) {
        this.showTree = true;
      }
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
    // 移除监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.handleScreenWidthChange);
    }
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.wd = "";
      this.queryParams.purpose = "";
      this.queryParams.type = "";
      this.queryParams.knowledge = "";
      this.queryParams.course = "";
      this.category = "";

      // 重置时重新获取所有知识点
      this.getKnowledge();

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 强制刷新布局，用于处理布局渲染问题
    refreshLayout() {
      this.isMobile = window.matchMedia('(max-width: 767px)').matches;
      this.$forceUpdate();
      this.$nextTick(() => {
        // 确保DOM完全更新后再次检查状态
        this.isMobile = window.matchMedia('(max-width: 767px)').matches;
        if (!this.isMobile) {
          this.showTree = true;
        }
        // 刷新列表
        this.getList();
      });
    },
    getBasicData() {
      // 获取所有知识点
      this.getKnowledge();
    },
    getKnowledge() {
      console.log("获取知识点，category参数:", this.category);
      this.knowledgeOptions = [];

      listKnowledge({
        page_size: 10000000,
        page: 1,
        category: this.category,
      }).then((response) => {
        if (response && response.results) {
          this.knowledgeOptions = response.results;
          console.log("获取到的知识点列表:", this.knowledgeOptions);
        } else {
          this.knowledgeOptions = [];
          console.log("没有获取到知识点数据");
        }
      }).catch((error) => {
        console.error("获取知识点失败:", error);
        this.knowledgeOptions = [];
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // console.log(2212121999, this.queryParams)
      getQuestion(this.queryParams).then((response) => {
        this.List = response.results;
        this.loading = false;
        this.total = response.count;
      });
    },
    getCategoryOptions() {
      categoryList({ page_size: 100000, parentId: "" }).then((res) => {
        this.categoryOptions = res;
      });
    },
    /** 查询列表 */
    getList1(data, parentId) {
      console.log("题库分类选择:", data, parentId);

      // 重置查询参数
      this.queryParams.course = "";
      this.queryParams.knowledge = "";
      this.category = '';

      if (parentId == null) {
        // 没有父级，选择的是顶级分类
        this.queryParams.course = data.id;
        this.queryParams.page = 1;
        this.category = data.id; // 修正：应该使用data.id作为category
        console.log("选择顶级分类", this.queryParams.course, "category:", this.category);
      } else {
        // 有父级，选择的是子分类
        this.queryParams.course = parentId;
        this.queryParams.page = 1;
        this.category = data.id;
        console.log("选择子分类", this.queryParams.course, "category:", this.category);
      }

      // 重新获取该分类下的知识点
      this.getKnowledge();

      // 重新获取题目列表
      this.getList();
    },

    handleAdd() {
      this.reset();
      this.$router.push({ path: "newQuestion" });
    },
    handleDelete(row) {
      this.$confirm('是否确认删除题目："' + row.stem + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delQuestion(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleUpdate(row) {
      this.$router.push({
        name: "Newquestion",
        params: { id: row.id },
      });
    },

    reset() {
      this.form = {
        stem: "",
        option: [
          { name: "A", content: "", is_right: false },
          { name: "B", content: "", is_right: false },
          { name: "C", content: "", is_right: false },
          { name: "D", content: "", is_right: false },
        ],
        // is_right: false,
      };
    },
    load() {
      this.count += 2;
    },
    //上传结果 关闭弹框
    resultsClose() {
      this.resultsUpload = false;
      this.tableResultsData = [];
      this.warningTitle = "";
    },
    //取消上传 关闭弹框
    uploadClose() {
      this.$refs.upload.clearFiles(); //清除上传文件列表
      this.upload.open = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //取消上传文件
    cancleFileForm() {
      this.$refs.upload.clearFiles();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.formData = {};
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功
    handleFileSuccess(response) {
      this.uploadClose();
      this.$refs.upload.clearFiles();
      // console.log(888, response);
      if (response.res.failed == 0) {
        this.failLoad = false;
      }
      this.formData = {};
      this.resultsUpload = true;
      this.upload.isUploading = false;
      this.tableResultsData = response.res.msg;
      this.warningTitle = `共上传<span style="font-weight:bold"> ${response.res.count} </span>道,其中上传成功 ${response.res.succed} 道,上传失败<span style="color:red"> ${response.res.failed}</span> 道`;
      this.getList();
    },
    // 文件上传失败
    handleFileError(err) {
      this.msgError("上传失败，请检查试题模板");
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    handleUploadClick() {
      this.upload.open = true;
      this.failLoad = true;
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    // 表格多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      
      this.$confirm(`是否确认批量删除选中的 ${this.selectedRows.length} 条题目?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 显示加载遮罩
        this.loading = true;
        
        // 记录成功和失败的数量
        let successCount = 0;
        let failCount = 0;
        
        // 使用Promise.all和map来并行处理删除请求
        const deletePromises = this.selectedRows.map(row => {
          return delQuestion(row.id)
            .then(() => {
              successCount++;
            })
            .catch(error => {
              failCount++;
              console.error(`删除题目 ID: ${row.id} 失败:`, error);
            });
        });
        
        Promise.all(deletePromises)
          .then(() => {
            this.getList();
            this.msgSuccess(`批量删除完成, 成功: ${successCount}, 失败: ${failCount}`);
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    handleSelectAll(val) {
      this.selectAll = val;
      if (val) {
        this.selectedRows = [...this.List];
        this.selectedRowKeys = this.List.map(item => item.id);
      } else {
        this.selectedRows = [];
        this.selectedRowKeys = [];
      }
    },
    handleItemSelect(val, item) {
      if (val) {
        this.selectedRows.push(item);
        this.selectedRowKeys.push(item.id);
      } else {
        this.selectedRows = this.selectedRows.filter(row => row.id !== item.id);
        this.selectedRowKeys = this.selectedRowKeys.filter(id => id !== item.id);
      }
      // 检查是否所有项目都被选中
      this.selectAll = this.selectedRows.length === this.List.length;
    },
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    // 处理屏幕宽度变化
    handleScreenWidthChange(e) {
      this.screenWidth = document.body.clientWidth;
    },
    // 切换卡片展开状态
    toggleExpand(index) {
      const position = this.expandedCards.indexOf(index);
      if (position !== -1) {
        this.expandedCards.splice(position, 1);
      } else {
        this.expandedCards.push(index);
      }
    },
    // 添加getTreeselect方法
    getTreeselect() {
      // 获取树形选择数据
      categoryList({ page_size: 100000, parentId: "" }).then((res) => {
        this.categoryOptions = res;
      });
    },
    // 添加getknowledgeOptions方法
    getknowledgeOptions() {
      // 获取知识点选项数据
      console.log("getknowledgeOptions - category参数:", this.category);

      listKnowledge({
        page_size: 10000000,
        page: 1,
        category: this.category,
      }).then((response) => {
        if (response && response.results) {
          this.knowledgeOptions = response.results;
          console.log("getknowledgeOptions - 获取到的知识点:", this.knowledgeOptions);
        } else {
          this.knowledgeOptions = [];
        }
      }).catch((error) => {
        console.error("getknowledgeOptions - 获取知识点失败:", error);
        this.knowledgeOptions = [];
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

.mobile-tree-container {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
  
  .mobile-tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    
    span {
      font-size: 16px;
      font-weight: bold;
    }
    
    .el-button {
      padding: 5px 12px;
      
      i {
        margin-right: 3px;
      }
    }
  }
}

.mobile-tree-toggle {
  margin-bottom: 15px;

  .el-button {
    font-weight: bold;
    letter-spacing: 1px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    
    i {
      margin-right: 5px;
      font-size: 14px;
    }
  }
}

.mobile-search {
  margin-bottom: 15px;
}

.mobile-form {
  .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;

    .el-form-item__label {
      display: block;
      text-align: left;
      padding: 0 0 5px;
    }

    .el-select, .el-input {
      width: 100%;
    }
  }
}

.mobile-toolbar {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.mobile-dialog-footer {
  display: flex;
  justify-content: space-between;
}

.mobile-card-view {
  margin-top: 15px;
  
  .mobile-selection-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background: #f5f7fa;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  }
  
  .mobile-card {
    margin-bottom: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.99);
    }
    
    /deep/ .el-card__header {
      padding: 12px 15px;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .card-header {
      display: flex;
      align-items: center;
      
      .question-meta {
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        
        .question-type {
          font-weight: bold;
          font-size: 15px;
          line-height: 1.2;
        }
        
        .question-score {
          font-size: 12px;
          color: #909399;
          margin-top: 2px;
        }
      }
      
      .card-actions {
        margin-left: auto;
        display: flex;
        
        i {
          font-size: 18px;
        }
      }
    }
    
    .card-content {
      padding: 10px 0;
      
      .question-stem {
        margin: 5px 0 15px;
        font-size: 14px;
        line-height: 1.6;
        
        /deep/ img {
          max-width: 100%;
          height: auto;
          border-radius: 4px;
        }
        
        /deep/ p {
          margin-bottom: 8px;
        }
      }
      
      .question-info {
        margin: 10px 0;
      }
      
      .question-options {
        margin: 15px 0;
        font-size: 14px;
        
        p {
          margin: 10px 0;
          padding: 8px 12px;
          background-color: #fafafa;
          border-radius: 6px;
          border-left: 3px solid #eaeaea;
        }
      }
      
      .question-answer {
        margin-top: 15px;
        font-size: 14px;
        padding: 10px 15px;
        background-color: rgba(245, 247, 250, 0.7);
        border-radius: 6px;
        font-weight: 500;
      }
      
      .card-toggle {
        text-align: center;
        margin: 12px 0 5px;
        
        .el-button {
          width: 100%;
          padding: 10px 0;
          font-size: 13px;
          
          i {
            margin-left: 5px;
            font-weight: bold;
          }
        }
      }
    }
  }
  
  .mobile-batch-actions {
    position: sticky;
    bottom: 15px;
    margin-top: 20px;
    text-align: center;
    z-index: 10;
    
    .el-button {
      width: 80%;
      padding: 12px 20px;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    }
  }
  
  .empty-data {
    text-align: center;
    padding: 40px 0;
    color: #909399;
    
    i {
      font-size: 40px;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 14px;
    }
  }
}

@media screen and (max-width: 768px) {
  .mobile-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .mobile-action-buttons {
    margin-top: 10px;
  }

  .mobile-card-list {
    margin-top: 15px;
    
    .mobile-card {
      margin-bottom: 15px;
      
      .mobile-card-header {
        margin-bottom: 15px;

        .card-title {
          display: flex;
          align-items: center;
          font-size: 16px;
          margin-bottom: 8px;
          
          .question-number {
            margin-right: 5px;
          }
          
          .question-type {
            font-size: 14px;
            margin-right: 10px;
          }
          
          .question-score {
            font-size: 14px;
            margin-left: auto;
          }
        }
        
        .card-content {
          font-size: 14px;
          line-height: 1.5;
        }
      }
      
      .mobile-card-info {
        margin-bottom: 12px;
        padding: 5px 0;
        border-bottom: 1px solid #f0f0f0;
        
        .info-label {
          color: #606266;
          font-size: 14px;
        }
        
        .info-value {
          font-size: 14px;
          word-break: break-all;
        }
      }
      
      .mobile-card-detail {
        background-color: #f9f9f9;
        padding: 8px;
        margin: 10px 0;
        border-radius: 4px;
        
        .question-option {
          margin-bottom: 8px;
          font-size: 14px;
        }
        
        .question-answer {
          padding-top: 8px;
          border-top: 1px dashed #e0e0e0;
          font-weight: bold;
        }
      }
      
      .mobile-card-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 15px;
        
        .el-button {
          padding: 0;
          margin-right: 15px;
        }
      }
    }
  }
  
  .mobile-pagination {
    margin-top: 20px;
    
    .mobile-pagination-wrapper {
      .pagination-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .el-pagination__sizes {
          width: 100px;
        }
      }
      
      .bottom-row {
        display: flex;
        justify-content: center;
        
        .el-pagination {
          padding: 0;
          text-align: center;
        }
      }
    }
  }
  
  .mobile-tree-container {
    background-color: #fff;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .mobile-tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 10px;
      
      span {
        font-weight: bold;
        font-size: 16px;
      }
    }
  }

  // 弹窗样式
  .mobile-dialog {
    .el-dialog__body {
      padding: 15px !important;
    }
    
    .el-form-item {
      margin-bottom: 15px;
    }
    
    .dialog-footer {
      .el-button {
        width: 100%;
        margin-left: 0 !important;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
